package com.xtayfjpk.security;


import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.junit.Test;

public class SecretKeyTest {
	private static final String ALGORITHM = "AES";
	
	@Test
	public void testEncrypt() throws Exception {
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		SecretKey key = KeyGenerator.getInstance(ALGORITHM).generateKey();
		writeSecretKey("xtayfjpk.key", key, true);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		//加密
		String myInfo = "我的明文";
		byte[] results = cipher.doFinal(myInfo.getBytes());
		writeFile("content.dat", results);
	}
	
	
	
	@Test
	public void testDecrypt() throws Exception {
		SecretKey key = readSecretKey("xtayfjpk.key", true);
		
		byte[] contents = readFile("content.dat");
		//解密
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] origins = cipher.doFinal(contents);
		System.out.println(new String(origins));
	}
	
	public byte[] readFile(String path) throws Exception {
		FileInputStream cntInput = new FileInputStream(path);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int b = -1;
		while((b=cntInput.read())!=-1) {
			baos.write(b);
		}
		cntInput.close();
		byte[] contents = baos.toByteArray();
		baos.close();
		return contents;
	}
	
	public void writeFile(String path, byte[] content) throws Exception {
		FileOutputStream fos = new FileOutputStream(path);
		fos.write(content);
		fos.close();
	}
	
	public SecretKey readSecretKey(String path, boolean encoded) throws Exception {
		if(encoded) {
			byte[] keyData = readFile(path);
			KeySpec keySpec = new DESKeySpec(keyData);
			SecretKey key = SecretKeyFactory.getInstance(ALGORITHM).generateSecret(keySpec);
			return key;
		} else {
			FileInputStream fis = new FileInputStream(path);
			ObjectInputStream bis = new ObjectInputStream(fis);
			Object object = bis.readObject();
			bis.close();
			return (SecretKey) object;
		}
	}
	
	public void writeSecretKey(String path, SecretKey secretKey, boolean encoded) throws Exception {
		FileOutputStream fos = new FileOutputStream(path);
		if(encoded) {
			fos.write(secretKey.getEncoded());
			fos.close();
		} else {
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(secretKey);
			oos.close();
		}
	}
}
